package org.monitor.controller.applog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.monitor.config.MonitorConfig;
import org.monitor.http.RestResult;
import org.monitor.kit.FileKit;
import org.monitor.model.AppMonitorManager;
import org.monitor.model.MonitorStateManager;
import org.monitor.servlet.controller.Controller;


/**
 * 监控停启用控制
 * @author zhaojjd
 *
 */
public class AppSettingController extends Controller {
	
	private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
	
	public void start(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		
		//启动状态监控
		MonitorStateManager.getAppInstance().start(ip, port, monitor);
		
		//启动日志监控
		AppMonitorManager.getInstance(ip, port).startMonitor(monitor);
		
		RestResult rst = new RestResult();
		renderJson(rst);
	}
	
	public void stop(){
		getPairs().checkRequired("ip", "port");
		
		String ip = getPair("ip");
		String port = getPair("port");
		String monitor = getPair("monitor");
		//停止日志监控
		AppMonitorManager.getInstance(ip, port).stopMonitor(monitor);
		File tmpLogFile = null;
		for (int i = 0; i < 3; i++) {
			tmpLogFile = AppMonitorManager.getInstance(ip, port).obtainMonitorLog(monitor);
			if(tmpLogFile != null){
				break;
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			}
		}
		
		RestResult rst = new RestResult();
		if(tmpLogFile != null){
			String filename = format.format(new Date()) + ".log";
			File distFile = getStoreFile(ip, port, monitor, filename);
			rst = moveLogFile(tmpLogFile, distFile);
			if(rst.getState() == 0){
				//释放日志监控
				AppMonitorManager.getInstance(ip, port).release();
				//停止状态监控
				MonitorStateManager.getAppInstance().stop(ip, port, monitor);
			}
		}else {
			rst.setState(-1);
			rst.setMsg("日志操作出现错误，请刷新页面后重试！");
		}
		
		renderJson(rst);
	}
	
	private RestResult moveLogFile(File tmpLogFile, File distFile) {
		RestResult rst = new RestResult();
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			is = new FileInputStream(tmpLogFile);
			fos = new FileOutputStream(distFile);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			fos.flush();
			rst.setData(distFile.getPath());
		}catch(Exception e){
			rst.setState(-1);
			rst.setMsg(e.getMessage());
		}finally {
			FileKit.close(is);
			FileKit.close(fos);
		}
		return rst;
	}

	private File getStoreFile(String ip, String port, String monitor, String filename) {
		File storeFile = null;
		
		String storeDir = MonitorStateManager.getAppInstance().getMonitorDir(ip, port, monitor).toString();
		File store = new File(storeDir);
		if(!store.exists()){
			store.mkdirs();
		}
		
		String storeFilename = getStoreFilename(filename, store);
		storeFile = new File(store.getPath() + File.separator + storeFilename);
		if(storeFile.exists()){
			storeFile.delete();
		}
		
		return storeFile;
	}

	private String getStoreFilename(String filename, File store) {
		String storeFilename = null;
		if(MonitorConfig.get().override()){
			storeFilename = filename;
		}else {
			int index = filename.lastIndexOf(".");
			final String baseName = index != -1 ?filename.substring(0, index) : filename ;
			String suffix = index != -1 ? filename.substring(index + 1) : null;
			
			String[] files = store.list(new FilenameFilter() {
				@Override
				public boolean accept(File dir, String name) {
					return name.startsWith(baseName);
				}
			});
			
			storeFilename = baseName;
			if(files != null && files.length > 0){
				storeFilename = storeFilename + "_" + files.length;
			}
			if(suffix != null){
				storeFilename = storeFilename + "." + suffix;
			}
		}
		return storeFilename;
	}
	
}
